/**
 * 
 */
package com.ez.supervise.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.views.freemarker.FreemarkerManager;

import com.ez.supervise.action.base.BaseAction;
import com.opensymphony.xwork2.util.FileManager;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.StringTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * @author searph.wang
 * @email searph.wang@gmail.com
 * @Created at 2009-10-28
 * 
 */
@SuppressWarnings("unchecked")
public class FreemarkerUtil {
    protected static Log log = LogFactory.getLog(FreemarkerUtil.class);

    private static Configuration conf = null;// string

    private static Configuration freemarkerCfg = null; // file

    private final static String AUTO_IMPORT = "auto_import";

    private FreemarkerUtil() {
	super();
    }

    public static Configuration getConfiguration() {
	if (conf == null) {
	    conf = new Configuration();
	    conf.setObjectWrapper(new DefaultObjectWrapper());
	    conf.setTemplateLoader(new StringTemplateLoader());
	    try {
		InputStream in = FileManager.loadFile("freemarker.properties", FreemarkerManager.class);
		if (in != null) {
		    Properties p = new Properties();
		    p.load(in);
		    p.remove(AUTO_IMPORT);
		    conf.setSettings(p);
		}
	    } catch (IOException e) {
		log.error("Error while loading freemarker settings from /freemarker.properties", e);
	    } catch (TemplateException e) {
		log.error("Error while loading freemarker settings from /freemarker.properties", e);
	    }
	}

	return conf;
    }

    public static Configuration getFreemakrerConfiguration(String templatePath) {
	if (freemarkerCfg == null) {
	    freemarkerCfg = new Configuration();
	    freemarkerCfg.setObjectWrapper(new DefaultObjectWrapper());
	    freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
	    try {
		freemarkerCfg.setTemplateLoader(new FileTemplateLoader());
		freemarkerCfg.setDirectoryForTemplateLoading(new File(templatePath));
		InputStream in = FileManager.loadFile("freemarker.properties", FreemarkerManager.class);
		if (in != null) {
		    Properties p = new Properties();
		    p.load(in);
		    p.remove(AUTO_IMPORT);
		    freemarkerCfg.setSettings(p);
		}
	    } catch (IOException e) {
		log.error("Error while loading freemarker settings from /freemarker.properties", e);
	    } catch (TemplateException e) {
		log.error("Error while loading freemarker settings from /freemarker.properties", e);
	    }
	}

	return freemarkerCfg;
    }

    public static Configuration getFreemakrerConfiguration() {
	return getFreemakrerConfiguration(BaseAction.FREEMARK_TEMPLATE_PATH);
    }

    public static boolean putTemplate(Configuration cfg, String stringTemplate) {
	try {
	    TemplateLoader templateLoader = cfg.getTemplateLoader();
	    ((StringTemplateLoader) templateLoader).putTemplate(stringTemplate, stringTemplate);
	} catch (Exception e) {
	    log.error("Error putTemplate : ", e);
	    return false;
	}
	return true;
    }

    public static boolean putTemplate(String stringTemplate) {
	try {
	    Configuration cfg = getConfiguration();
	    TemplateLoader templateLoader = cfg.getTemplateLoader();
	    if (templateLoader.findTemplateSource(stringTemplate) == null) {
		((StringTemplateLoader) templateLoader).putTemplate(stringTemplate, stringTemplate);
	    }
	} catch (Exception e) {
	    log.error("Error process freemarker : ", e);
	    return false;
	}
	return true;
    }

    public static String processTemplate(String stringTemplate, Map root) {
	Configuration cfg = getConfiguration();
	try {
	    Template template = cfg.getTemplate(stringTemplate);
	    StringWriter writer = new StringWriter();
	    template.process(root, writer);
	    // System.out.println(writer.toString());
	    return writer.toString();
	} catch (Exception e) {
	    log.error("Error process freemarker : ", e);
	    return null;
	}
    }

    /**
     * 生成静态文件
     * 
     * @param ftlTemplate
     *            ftl模版文件
     * @param contents
     *            ftl要用到的动态内容
     * @param savePath
     *            文件保存路径
     * @param fileName
     *            保存文件名
     * @throws IOException
     * @throws TemplateException
     */
    public static boolean createHtml(String ftlTemplate, Map contents, String savePath, String fileName) {
	Configuration cfg = getFreemakrerConfiguration();
	try {
	    Template temp = cfg.getTemplate(ftlTemplate);
	    File file = new File(savePath);
	    Writer out = new OutputStreamWriter(new FileOutputStream(savePath + "/" + fileName), "UTF-8");
	    temp.process(contents, out);
	    out.flush();
	} catch (Exception e) {
	    log.error("File: " + savePath  + "/" + fileName);
	    log.error("Error create html fail : ", e);
	    return false;
	}
	return true;
    }
    
    public static String getSystemEncode(){
	String encode = System.getProperties().getProperty("sun.jnu.encoding");
	if(encode == null){
	    encode = System.getenv("file.encoding");
	}
	if(encode == null){
	    encode = "UTF-8";
	}
	return encode;
    }

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
//	Configuration conf = getConfiguration();
//	String ftlTemplate = "txl.ftl";
//	
//	String path = "E:/workspace/supervise/WebRoot/template";
//	System.out.println(new File(path, ftlTemplate).exists());
//	Configuration conf = getFreemakrerConfiguration();
//	Template temp = conf.getTemplate(ftlTemplate);
	System.out.println(Charset.defaultCharset());
	 Properties prop = System.getProperties();
	    System.out.println(System.getenv("sun.jnu.encoding"));
	    prop.list(System.out);
    }
    
    

}
